package com.woniu.user.service.impl;

import com.woniu.common.entity.ResultCode;
import com.woniu.common.exception.LifeException;
import com.woniu.user.dto.UserRegisterDTO;
import com.woniu.user.pojo.User;
import com.woniu.user.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.user.service.IUserService;
import com.woniu.user.vo.UserLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author hushunlai
 * @since 2023-05-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserLoginVO loginByPassword(String mobile, String password) {
        //根据账号查询用户
        User user = userMapper.getByMobile(mobile);
        if (user == null) {
            return null;
        }
        //密码比较
        if (!BCrypt.checkpw(password, user.getPassword())) {
            //密码不正确
            return null;
        }
        //创建一个vo
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, userLoginVO);
        return userLoginVO;
    }

    @Override
    public UserLoginVO getByMobile(String mobile) {
        User user = userMapper.getByMobile(mobile);
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, userLoginVO);
        return userLoginVO;
    }

    @Override
    public void register(UserRegisterDTO userRegisterDTO) {
        //检验手机号是否被注册
        User user = userMapper.getByMobile(userRegisterDTO.getMobile());
        if (user != null) {
            //该手机号已经注册
            throw new LifeException("手机号码已经被注册", ResultCode.USER_HAS_EXISTED);
        }
        //密码加密
        String newPassword = BCrypt.hashpw(userRegisterDTO.getPassword(), BCrypt.gensalt());
        //创建user对象并设置初始值
        user = new User();
        user.setPassword(newPassword);
        user.setMobile(userRegisterDTO.getMobile());
        user.setUserType((byte) 0);
        user.setCreateTime(new Date());
        //保存用户信息
        userMapper.insert(user);
    }

    @Override
    public void updateAmount(String mobile, BigDecimal amount) {
        userMapper.updateAmount(mobile, amount);
    }

    /**
     * 增加比特币数量
     */
    @Override
    public void addAmount(String mobile, BigDecimal amount) {
        userMapper.addAmount(mobile, amount);
    }

    @Override
    public void updateStoreId(Integer storeId, String mobile) {
        userMapper.updateStoreId(mobile, storeId);
    }
}
